import TagGroup from '@/components/TagGroup';
import { listCuesIndustry } from '@/services/api/api-cues-industry';
import { getCuesSubmitDetails, saveCuesSubmit } from '@/services/api/api-cues-submit';
import {
    CheckCircleTwoTone,
    FileSearchOutlined,
    PlusOutlined,
    SendOutlined,
} from '@ant-design/icons';
import { ModalForm, ProCard, ProFormCascader, ProList } from '@ant-design/pro-components';
import ProForm, {
    DrawerForm,
    ProFormInstance,
    ProFormSelect,
    ProFormText,
    ProFormTextArea,
} from '@ant-design/pro-form';
import { ActionType } from '@ant-design/pro-table';
import { Button, Cascader, Spin, message } from 'antd';
import FormItem from 'antd/es/form/FormItem';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';
import AddActivePreview from './AddActivePreview';
import { initSaveActiveTreeAssignOrganization, selectCuesActive } from '@/services/api/api-cues-active';
import { DefaultOptionType } from 'antd/es/select';
import TextEditor from '../../components/TextEditor';
import UploadDragger from '../../components/UploadDragger';

interface EditActiveProps {
    id: string;
    onRefurbish: () => void;
}

const EditActive: React.FC<EditActiveProps> = ({ onRefurbish, id }) => {
    const access = useAccess();

    const actionRef = useRef<ActionType>();

    const formRef = useRef<ProFormInstance>();

    const [industrys, setIndustrysState] = useState<any[]>([]);

    const [openAddSubmit, setOpenAddSubmit] = useState<boolean>(false);

    const [openAddSubmitPreview, setOpenAddSubmitPreview] = useState<boolean>(false);
    const [previewData, setPreviewData] = useState<CuesActiveBo.AddActivePreview>();

    const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

    const [initialValuesData, setInitialValuesDataState] = useState<CuesSubmitData.SubmitDetails>();

    const [green, setGreen] = useState<boolean>(false);
    /**
     * 指派单位数据
     */
    const [treeAssignOrganizationData, setTreeAssignOrganizationDataState] = useState<DataNode[]>();

    /**
     * 预备Tree结构数据
     * @param data
     */
    function readyTreeData(data: AdminOrganizationData.Organization[]): any {
        const treeData = new Array();
        if (data) {
            data.forEach((val) => {
                treeData.push({
                    label: val.name,
                    value: val.id,
                    disabled: val.isFolder === 1  && val.isOrganization === 0 && val.children === undefined,
                    children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
                });
            });
        }
        return treeData;
    }

    /**
     * 加载 保存 推送 单位
     */
    const loadInitSaveActiveTreeAssignOrganization = async () => {
        try {
            const response = await initSaveActiveTreeAssignOrganization();
            if (response.code === 0) {
                setTreeAssignOrganizationDataState(readyTreeData(response.data));
            }
        } catch (error) { }
    };
    /**
 * 级联组件 搜索筛选
 * @param inputValue
 * @param path
 * @returns
 */
    const filter = (inputValue: string, path: DefaultOptionType[]) =>
        path.some(
            (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
        );

    /**
     * 获取 详情
     * @param key
     */
    const getSubmitDetails = async () => {
        try {
            const response = await selectCuesActive({ id });
            if (response.code === 0) {
                console.log(response.data);
                formRef.current?.setFieldsValue({
                    articleName: response.data?.articleName,
                    articleIndustryIds: response.data?.articleIndustrys,
                    articleLabels: response.data?.articleLabels.map((item) => item.label),
                    articleContent: response.data?.articleContent,
                    remarks: response.data?.remarks,
                    articleAttachments: response.data?.articleAttachments,
                    assignOrganizationIds: response.data?.cascaderAssignOrganizations
                });
                setInitialValuesDataState(response.data);
            }
        } catch (error) { }
    };
    // /**
    //  * 加载权限详情
    //  * @param key
    //  */
    // const getCuesIndustryData = async () => {
    //     try {
    //         const response = await listCuesIndustry();

    //         setIndustrysState(
    //             response.data.map((item) => {
    //                 return { label: item.name, value: item.id };
    //             }),
    //         );
    //     } catch (error) { }
    // };



    return (
        <DrawerForm
            key="drawer_form_add_submit"
            title="编辑线索"
            drawerProps={{
                maskClosable: false,
                // destroyOnClose: true,
                width: '100%',
            }}
            formRef={formRef}
            trigger={
                <a>
                    编辑
                </a>
            }
           visible={openAddSubmit}
            onVisibleChange={(visible) => {
                getSubmitDetails();
                setOpenAddSubmit(visible);
                if (visible) {
                    loadInitSaveActiveTreeAssignOrganization();
                    // getCuesIndustryData();
                }
            }}
            layout="horizontal"
            submitter={{
                searchConfig: {
                    submitText: (
                        <>
                            <FileSearchOutlined /> 预览
                        </>
                    ),
                },
                render: (props, defaultDoms) => {
                    return [
                        defaultDoms,
                        <Button
                            key="button_add_submit"
                            icon={<SendOutlined />}
                            type="primary"
                            style={{
                                background: '#87d068',
                            }}
                            onClick={() => {
                                /**
                                 * ======================
                                 * 直接发布
                                 * ======================
                                 */
                                const values = formRef.current?.getFieldsValue();

                                if (!(values.articleName !== undefined && values.articleName.length > 0)) {
                                    message.warning('请输入标题');
                                    return;
                                }

                                if (
                                    !(values.articleIndustryIds !== undefined && values.articleIndustryIds.length > 0)
                                ) {
                                    message.warning('请选择至少一个行业');
                                    return;
                                }

                                if (!(values.articleLabels !== undefined && values.articleLabels.length > 0)) {
                                    message.warning('请输入至少一个标签');
                                    return;
                                }

                                if (!(values.articleContent !== undefined && values.articleContent.length > 0)) {
                                    message.warning('请输入内容');
                                    return;
                                }

                                setModalFormOpenState(true);
                            }}
                        >
                            提交
                        </Button>,
                        <AddActivePreview
                            key="add_submit_preview"
                            onSubmit={() => {
                                setOpenAddSubmit(false);
                                onRefurbish();
                            }}
                           visible={openAddSubmitPreview}
                            onVisibleChange={(open) => {
                                setOpenAddSubmitPreview(open);
                            }}
                            details={previewData}
                        />,
                        <ModalForm
                            key={'modal_form_add_submit'}
                            title={
                                <>
                                    <CheckCircleTwoTone
                                        style={{
                                            marginRight: 8,
                                        }}
                                        twoToneColor="#87d068"
                                    />
                                    确认提交
                                </>
                            }
                            autoFocusFirstInput
                            modalProps={{
                                width: '100%',
                                destroyOnClose: true,
                            }}
                           visible={modalFormOpen}
                            onVisibleChange={setModalFormOpenState}
                            submitTimeout={2000}
                            submitter={{
                                submitButtonProps: {
                                    type: 'primary',
                                    style: { background: '#87d068' },
                                },
                            }}
                            onFinish={async () => {
                                const values = formRef.current?.getFieldsValue();

                                if (
                                    values.articleAttachments !== undefined &&
                                    values.articleAttachments.length > 0
                                ) {
                                    const articleAttachments = values.articleAttachments.map(
                                        (item: { response: { data: { id: any } } }) => {
                                            return item.response.data.id;
                                        },
                                    );

                                    values.articleAttachments = articleAttachments;
                                }

                                const response = await saveCuesSubmit({
                                    id: id,
                                    topicId: initialValuesData?.topicId,
                                    articleName: values?.articleName,
                                    articleIndustryIds: values?.articleIndustryIds,
                                    articleLabels: values?.articleLabels,
                                    remarks: values?.remarks,
                                    articleContent: values?.articleContent,
                                    articleAttachments: values?.articleAttachments,
                                    createdSource: 1,
                                });

                                if (response.code === 0) {
                                    message.success('提交成功');
                                    setOpenAddSubmit(false);
                                    onRefurbish();
                                    return true;
                                } else {
                                    return false;
                                }
                            }}
                        />,
                    ];
                },
            }}
            onFinish={async (values) => {
                /**
                 * ======================
                 * 预览发布
                 * ======================
                 */
                if (!(values.articleName !== undefined && values.articleName.length > 0)) {
                    message.warning('请输入标题');
                    return;
                }

                if (!(values.articleIndustryIds !== undefined && values.articleIndustryIds.length > 0)) {
                    message.warning('请选择至少一个行业');
                    return;
                }

                if (!(values.articleLabels !== undefined && values.articleLabels.length > 0)) {
                    message.warning('请输入至少一个标签');
                    return;
                }

                if (!(values.articleContent !== undefined && values.articleContent.length > 0)) {
                    message.warning('请输入内容');
                    return;
                }

                console.log(values.articleIndustryIds);

                // const articleIndustrys = values.articleIndustryIds?.map((item) => {
                //     const industry = industrys.find((e) => e.value === item);
                //     return industry;
                // });

                setPreviewData({
                    id: id,
                    topicId: initialValuesData?.topicId,
                    topicName: initialValuesData?.topicName,
                    articleName: values.articleName,
                    articleIndustrys: values.articleIndustryIds,
                    articleLabels: values.articleLabels,
                    remarks: values.remarks,
                    articleContent: values.articleContent,
                    createdSource: 1,
                    articleAttachments: values.articleAttachments,
                });

                setOpenAddSubmitPreview(true);
            }}
        >
            <Spin
                style={{
                    textAlign: 'center',
                }}
                spinning={initialValuesData === undefined}
            >
                <ProFormText
                    width="xl"
                    name="articleName"
                    label={
                        <>
                            <span
                                style={{
                                    color: '#ff4d4f',
                                    fontSize: 14,
                                    paddingRight: 4,
                                }}
                            >
                                *
                            </span>
                            标题
                        </>
                    }
                    fieldProps={{
                        allowClear: true,
                        maxLength: 200,
                    }}
                />
                <ProFormSelect
                    width="xl"
                    name="articleIndustryIds"
                    label={
                        <>
                            <span
                                style={{
                                    color: '#ff4d4f',
                                    fontSize: 14,
                                    paddingRight: 4,
                                }}
                            >
                                *
                            </span>
                            行业
                        </>
                    }
                    // options={industrys}
                    request={async () => {
                        const response = await listCuesIndustry();
                        return response.data.map((item) => {
                            return { label: item.name, value: item.id };
                        })
                    }}
                    fieldProps={{
                        mode: 'multiple',
                        labelInValue: true,
                        allowClear: true,
                    }}
                />
                <ProForm.Item
                    label={
                        <>
                            <span
                                style={{
                                    color: '#ff4d4f',
                                    fontSize: 14,
                                    paddingRight: 4,
                                }}
                            >
                                *
                            </span>
                            标签
                        </>
                    }
                    name="articleLabels"
                    extra={'最少输入一个'}
                >
                    <TagGroup />
                </ProForm.Item>
                <ProFormCascader
                    width="xl"
                    label={
                        <span
                            style={{
                                marginLeft: 11,
                            }}
                        >
                            报送
                        </span>
                    }
                    name="assignOrganizationIds"
                    placeholder="选择媒体"
                    extra="不选择，默认推送给所有媒体单位"
                    fieldProps={{
                        options: treeAssignOrganizationData,
                        // showSearch: { filter },
                        multiple: true,
                        removeIcon: true,
                        allowClear: true,
                        maxTagCount: 'responsive',
                        showCheckedStrategy: Cascader.SHOW_CHILD,
                    }}
                />
                <ProForm.Group>
                    <ProFormTextArea
                        name="remarks"
                        label={
                            <span
                                style={{
                                    marginLeft: 11,
                                }}
                            >
                                备注
                            </span>
                        }
                        width="xl"
                        fieldProps={{
                            allowClear: true,
                            rows: 2,
                            maxLength: 200,
                        }}
                    />
                </ProForm.Group>
                <ProCard ghost>
                    <ProCard colSpan={green ? '750px' : '1'} ghost>
                        <ProForm.Item
                            name="articleContent"
                            label={
                                <>
                                    <span
                                        style={{
                                            color: '#ff4d4f',
                                            fontSize: 14,
                                            paddingRight: 4,
                                        }}
                                    >
                                        *
                                    </span>
                                    线索内容
                                </>
                            }
                        >
                            {initialValuesData ? <TextEditor
                                onInit={(editor) => { }}
                                readonly={false}
                                onClick={(value) => { }}
                                defaultContent=""
                                tinyID='tinyId'
                            /> : <></>}
                        </ProForm.Item>
                    </ProCard>
                </ProCard>

                <FormItem
                    name="articleAttachments"
                    hidden={!access.线索征集x上报线索x附件}
                    label={
                        <span
                            style={{
                                marginLeft: 11,
                            }}
                        >
                            附件
                        </span>
                    }
                >
                    <UploadDragger
                        onPreview={(file) => { }}
                        access={{
                            isPicture: access.线索征集x上报线索x附件x图片,
                            isVideo: access.线索征集x上报线索x附件x视频,
                            isOffice: access.线索征集x上报线索x附件x办公,
                            isOther: access.线索征集x上报线索x附件x其他,
                        }}
                        url="/cues/attachment/save"
                        mode="submit"
                    />
                </FormItem>
            </Spin>
        </DrawerForm>
    );
};
export default EditActive;
